package club.banyuan.mbm;

import club.banyuan.mbm.util.ValidateUtil;
import com.alibaba.fastjson.JSONObject;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.stream.Collectors;

public class UserService {

    // 为每个用户分配一个唯一id
    private int idCount = 1;
    private List<User> userList = new CopyOnWriteArrayList<>();

//    private static final String REGEX_PWD = "\\S{6,20}";
//    private static final String REGEX_USER_NAME = "[a-zA-Z]\\w{5,19}";

    // 向列表中添加用户
    synchronized public void addUser(User user) {
        // 正则表达式匹配名字

//        if (!user.getName().matches(REGEX_USER_NAME)) {
//            throw new BadRequestException("用户名输入不合法");
//        }
//
//        if (!user.getPwd().matches(REGEX_PWD)) {
//            throw new BadRequestException("密码不合法");
//        }

        if (!user.getPwd().equals(user.getPwdConfirm())) {
            throw new BadRequestException("密码和确认密码不一致");
        }
        ValidateUtil.validate(user);

        Optional<User> any = userList.stream().filter(t -> t.getName().equals(user.getName()))
                .findAny();

        if (any.isPresent()) {
            // 用户名不合法
            throw new BadRequestException("用户名已存在");
        }
        // 为用户生成一个唯一的id
        user.setId(idCount++);
        userList.add(user);
    }

    // 删除用户
    synchronized public void deleteUser(int id) {
        // OK
        // Iterator<User> iterator = userList.iterator();
        // while (iterator.hasNext()) {
        //   if (iterator.next().getId() == id) {
        //     iterator.remove();
        //   }
        // }

        // 简写
        userList.removeIf(user -> user.getId() == id);

        // 错误代码
        // for (User user : userList) {
        //   if (user.getId() == id) {
        //     userList.remove(user);
        //   }
        // }
    }

    public User getUser(int id) {
        for (User user : userList) {
            if (user.getId() == id) {
                return user;
            }
        }
        return null;
    }

    synchronized public void updateUser(User user) {
//        if (!user.getName().matches(REGEX_USER_NAME)) {
//            throw new BadRequestException("用户名输入不合法");
//        }
//
//        if (!user.getPwd().matches(REGEX_PWD)) {
//            throw new BadRequestException("密码不合法");
//        }

        if (!user.getPwd().equals(user.getPwdConfirm())) {
            throw new BadRequestException("密码和确认密码不一致");
        }
        ValidateUtil.validate(user);
        User old = getUser(user.getId());
        if (old != null) {
            old.setName(user.getName());
            old.setPwd(user.getPwd());
            old.setUserType(user.getUserType());
        }
    }

    public int getIdCount() {
        return idCount;
    }

    public void setIdCount(int idCount) {
        this.idCount = idCount;
    }

    public List<User> getUserList() {
        return userList;
    }

    public void setUserList(List<User> userList) {
        this.userList = userList;
    }


    // 保存到指定路径下
    public void save() {
        String path = getPath();
        checkFileExist(path);
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(path))) {
            writer.write(JSONObject.toJSONString(this));
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    // 反序列化回来
    public static UserService load() {
        String path = getPath();
        checkFileExist(path);
        try (InputStream inputStream = new FileInputStream(path)) {

            return JSONObject
                    .parseObject(inputStream, UserService.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new UserService();

    }

    private static String getPath() {
        Properties properties = new Properties();
        try {
            properties.load(UserService.class.getResourceAsStream("/app.properties"));
        } catch (IOException e) {
            System.out.println("读取配置文件失败");
            System.exit(-1);
        }
        return properties.getProperty("user.store.path");
    }

    public User userLogin(User user) {
        for (User one : userList) {
            if (one.getName().equals(user.getName()) && one.getPwd().equals(user.getPwd())) {
                return one;
            }
        }
        return null;
    }

    private static void checkFileExist(String filePath) {
        File file = new File(filePath);
        if (!file.exists()) {
            File newFile = new File(file.getParent());
            newFile.mkdirs();
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public List<User> getUserList(User user) {
//        if (user == null || user.getName() == null || user.getName().trim().length() == 0){
//            return getUserList();
//        }
//        List<User> rlt = new ArrayList<>();
//        for (User one : userList) {
//            if (one.getName().contains(user.getName())) {
//                rlt.add(one);
//            }
//        }
//        return rlt;
        return userList.stream().filter(t -> t.getName().contains(user.getName())).collect(Collectors.toList());
    }


}
